package com.fs.system.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.FastByteArrayOutputStream;
import cn.hutool.core.lang.UUID;
import com.fs.common.config.FeiSiConfig;
import com.fs.common.constant.CacheConstants;
import com.fs.common.constant.Constants;
import com.fs.common.core.vo.AjaxResult;
import com.fs.common.util.RedisCache;
import com.fs.system.service.ISysConfigService;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author suke
 * @version 1.0
 * @title CaptchaController
 * @description  验证码Controller
 * @create 2024/7/23 11:00
 */
@RestController
public class CaptchaController {

    @Resource(name="captchaProducer")
    private Producer  captchaProducer;

    @Resource(name="captchaProducerMath")
    private Producer  captchaProducerMath;

    @Autowired
    private RedisCache redisCache;


    @Autowired
    private ISysConfigService sysConfigService;

    long i;





    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    public AjaxResult getCode() {
        AjaxResult ajaxResult = AjaxResult.success();
        //1.查询是否开启验证码
        boolean captchaEnabled = sysConfigService.selectCaptchaEnabled();
        ajaxResult.put("captchaOnOff",captchaEnabled);
        if (!captchaEnabled) { //没有开启验证码
            return  ajaxResult;
        }
        //如果开启了, 产生验证码
        //得到验证码类型
        String captchaType = FeiSiConfig.getCaptchaType();
        //capStr验证码的文本,  code: 存在redis的验证码结果
        String capStr=null, code=null;
        //验证码图片对象
        BufferedImage image = null;
        if("math".equals(captchaType)){ //数学算术表达式
               //产生验证码文本
            // 1+1=?@2
            String text = captchaProducerMath.createText();
            capStr = text.substring(0,text.lastIndexOf("@"));
            code  = text.substring(text.lastIndexOf("@")+1);
            //生成验证码图片
            image = captchaProducerMath.createImage(capStr);
        }else if("char".equals(captchaType)){ //字符表达式
           capStr = code =  captchaProducer.createText();
            image =captchaProducer.createImage(capStr);
        }
        //把验证码图片进行base64编码
        //把图片转换为字节数组
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image,"jpeg",os);
        } catch (IOException e) {
           return AjaxResult.error(e.getMessage());
        }
        //使用Base64编码
        String base64Str = Base64.encode(os.toByteArray());
        String base64Img = "data:image/jpeg;base64," +base64Str;
        //BASE64对密文进行传输加密时，可能出现\r\n
        //原因： RFC2045中有规定：即Base64一行不能超过76字符，超过则添加回车换行符。
        //解决方案: BASE64加密后，对\r\n进行去除
        base64Img= base64Img.replaceAll("\r|\n", "");

        //把code保存到redis中
        //生成一个UUID
        String uuid = UUID.randomUUID().toString(true);
        //验证码结果在redis保存2分钟,  验证码2分钟有效
        redisCache.setCacheObject(CacheConstants.CAPTCHA_CODE_KEY+uuid,code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        //响应数据给前端
        ajaxResult.put("img",base64Img);
        ajaxResult.put("uuid",uuid);
        return ajaxResult;
    }
}
